/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package modulos.reservacion.vista;

import basedatos.OperacionesBD;
import basedatos.ServicioBD;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import modulos.usuario.modelo.Usuario;
import modulos.reservacion.modelo.Servicio;
import vista.frmPrincipal;
import vista.modelo.OperacionesVarias;

/**
 *
 * @author Edulima
 */
public class iFrmServiciosAdmin extends javax.swing.JInternalFrame {

    private ArrayList<Object> listServicios;
    private Servicio mdfServicio;
    private DefaultListModel modeloServicio = new DefaultListModel();
    private Usuario usuario;

    /**
     * Creates new form iFrmReservaCita11
     */
    public iFrmServiciosAdmin(Usuario usuario) {
        initComponents();
        OperacionesVarias.cerrarVentanaEscape(this);
        this.usuario = usuario;
        listarServicios();
    }

    private void listarServicios() {
        listServicios = (ArrayList<Object>) OperacionesBD.listarPorUsuario("Servicio",usuario);
        modeloServicio.removeAllElements();
        for (Object obj : listServicios) {
            modeloServicio.addElement(((Servicio) obj));
        }
    }

    private Servicio getServicio(Servicio servicio) {
        servicio.setServicio(txtServicio.getText().trim());
        servicio.setCosto(Double.parseDouble(txtCosto.getText()));
        servicio.setUsuario(usuario);
        return servicio;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        btnEditar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        listadoServicios = new javax.swing.JList();
        btnCerrar = new javax.swing.JButton();
        btnNuevo = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        btnGuardar = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        txtCosto = new javax.swing.JTextField();
        txtServicio = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();

        setClosable(true);
        setTitle("Servicios");

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(96, 128, 165)));

        btnEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/icono_editar.png"))); // NOI18N
        btnEditar.setText("Editar");
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });

        listadoServicios.setBorder(javax.swing.BorderFactory.createTitledBorder("Listado de Servicios"));
        listadoServicios.setModel(modeloServicio);
        listadoServicios.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                listadoServiciosKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(listadoServicios);

        btnCerrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/agt_home.png"))); // NOI18N
        btnCerrar.setText("Cerrar");
        btnCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCerrarActionPerformed(evt);
            }
        });

        btnNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/add.png"))); // NOI18N
        btnNuevo.setText("Nuevo");
        btnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoActionPerformed(evt);
            }
        });

        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/delete.png"))); // NOI18N
        btnEliminar.setText("Eliminar");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnCerrar, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 14, Short.MAX_VALUE))
                    .addComponent(btnEliminar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnEditar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnNuevo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 413, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnNuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnEditar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnEliminar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 86, Short.MAX_VALUE)
                        .addComponent(btnCerrar))
                    .addComponent(jScrollPane1))
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(96, 128, 165)));

        jLabel1.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
        jLabel1.setText("Servicio:");

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/filesave.png"))); // NOI18N
        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
        jLabel2.setText("Costo:");

        txtCosto.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtCostoKeyTyped(evt);
            }
        });

        txtServicio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtServicioActionPerformed(evt);
            }
        });
        txtServicio.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtServicioKeyTyped(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("DejaVu Sans", 0, 13)); // NOI18N
        jLabel3.setText("$");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(3, 3, 3)
                .addComponent(jLabel1)
                .addGap(1, 1, 1)
                .addComponent(txtServicio, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(6, 6, 6)
                .addComponent(jLabel2)
                .addGap(1, 1, 1)
                .addComponent(txtCosto, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(3, 3, 3)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtServicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtCosto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(btnGuardar)
                    .addComponent(jLabel3))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed

        if (!txtServicio.getText().isEmpty() && !txtCosto.getText().isEmpty()) {
            if(OperacionesVarias.isDecimal(txtCosto.getText())){
            if (btnGuardar.getText().equalsIgnoreCase("Guardar")) {

                if (!ServicioBD.existe("Servicio", "servicio", txtServicio.getText(),usuario)) {
                    if (OperacionesBD.guardar(getServicio(new Servicio()))) {
                        JOptionPane.showMessageDialog(null, "Servicio guardado correctamente ...", "Guardar", JOptionPane.INFORMATION_MESSAGE);
                        listarServicios();
                        txtServicio.setText("");
                        txtCosto.setText("");
                    } else {
                        JOptionPane.showMessageDialog(null, "El servicio no se han podido guardar ...", "Guardar", JOptionPane.ERROR_MESSAGE);
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "El servicio ya existe", "Guardar", JOptionPane.WARNING_MESSAGE);
                }
            } else {
                if (OperacionesBD.modificar(getServicio(mdfServicio))) {
                    JOptionPane.showMessageDialog(null, "Servicio actualizado correctamente ...", "Actualizar", JOptionPane.INFORMATION_MESSAGE);
                    nuevo();
                    listarServicios();
                } else {
                    JOptionPane.showMessageDialog(null, "El Servicio no se han podido actualizar ...", "Actualizar", JOptionPane.ERROR_MESSAGE);
                }
            }
       
        }else{
                            JOptionPane.showMessageDialog(null, "EL costo ingresado no es valido", "Error de Ingreso", JOptionPane.WARNING_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(null, "Ingrese el servicio y su costo", "Datos Incompletos", JOptionPane.WARNING_MESSAGE);
        }

    }//GEN-LAST:event_btnGuardarActionPerformed

    private void nuevo() {
        txtServicio.setText("");
        txtCosto.setText("");
        btnEditar.setText("Editar");
        btnGuardar.setText("Guardar");
        mdfServicio = null;
    }

    private void txtServicioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtServicioActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtServicioActionPerformed

    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
        if (btnEditar.getText().equalsIgnoreCase("Editar")) {
            if (listServicios.size() > 0) {
                if (!listadoServicios.isSelectionEmpty()) {

                    mdfServicio = (Servicio) listServicios.get(listadoServicios.getSelectedIndex());
                    btnGuardar.setText("Actualizar");
                    btnEditar.setText("Cancelar");
                    txtServicio.setText(mdfServicio.getServicio());
                    txtCosto.setText(mdfServicio.getCosto() + "");
                } else {
                    JOptionPane.showMessageDialog(this, "Seleccione el Servicio que desea editar ...", "Editar Servicio", JOptionPane.WARNING_MESSAGE);

                }
            } else {
                JOptionPane.showMessageDialog(this, "No ha registrado ningun Servicio para poder editar ...", "Editar Servicio", JOptionPane.WARNING_MESSAGE);

            }
        } else {
            nuevo();
        }

    }//GEN-LAST:event_btnEditarActionPerformed

    private void btnCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCerrarActionPerformed
        dispose();
    }//GEN-LAST:event_btnCerrarActionPerformed

    private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
        nuevo();
    }//GEN-LAST:event_btnNuevoActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        if (listServicios.size() > 0) {
            if (!listadoServicios.isSelectionEmpty()) {
                mdfServicio = (Servicio) listServicios.get(listadoServicios.getSelectedIndex());

                if (JOptionPane.showConfirmDialog(this, "Realmente quiere eliminar el servicio:\n" + mdfServicio.getServicio(), "Eliminar servicio", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == 0) {
                    try {
                        if (OperacionesBD.eliminar(mdfServicio, mdfServicio.getIdServicio())) {
                            JOptionPane.showMessageDialog(this, "Servicio eliminado correctamente ...", "Eliminar Servicio", JOptionPane.INFORMATION_MESSAGE);
                            listarServicios();
                        } else {
                            JOptionPane.showMessageDialog(this, "El servicio no ha podido ser eliminado ...", "Eliminar Servicio", JOptionPane.ERROR_MESSAGE);
                        }
                    } catch (Exception ex) {
                        Logger.getLogger(iFrmServiciosAdmin.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } else {
                }
            } else {
                JOptionPane.showMessageDialog(this, "Seleccione el servicio que desea eliminar ...", "Eliminar Servicio", JOptionPane.WARNING_MESSAGE);

            }
        } else {
            JOptionPane.showMessageDialog(this, "No ha registrado ningun servicio para poder eliminar ...", "Eliminar servicio", JOptionPane.WARNING_MESSAGE);

        }
    }//GEN-LAST:event_btnEliminarActionPerformed

    private void txtServicioKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtServicioKeyTyped
        OperacionesVarias.ingresoSoloLetras(evt);
    }//GEN-LAST:event_txtServicioKeyTyped

    private void txtCostoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCostoKeyTyped
        OperacionesVarias.ingresoDecimales(evt);
    }//GEN-LAST:event_txtCostoKeyTyped

    private void listadoServiciosKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_listadoServiciosKeyReleased
            if(evt.getKeyCode()==KeyEvent.VK_DELETE){
                btnEliminarActionPerformed(null);
            }
    }//GEN-LAST:event_listadoServiciosKeyReleased

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCerrar;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnNuevo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList listadoServicios;
    private javax.swing.JTextField txtCosto;
    private javax.swing.JTextField txtServicio;
    // End of variables declaration//GEN-END:variables
}
